<?php
/**
 * 微信交互控制器
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Common;
class WeixinController extends Controller
{
    /**
     * 在微信平台上设置的对外 URL
     */
    public function api()
    {
        $echostr = I('get.echostr', '');
        if ($echostr != '') {
            // 判读验证是否通过
            if ($this->_valid()) {
                echo $echostr;
                exit;
            } else {
                echo "";
                exit;
            }
        } else {
            // 实际处理用户消息
            $this->_responseMsg();
        }
    }

    /**
     * 用于接入验证
     */
    private function _valid()
    {
        $token = $this->_get_token();
        if ($token == '') {
            return false;
        }
        $signature = I('signature');
        $timestamp = I('timestamp');
        $nonce = I('nonce');

        $tmp_arr = array($token, $timestamp, $nonce);
        sort($tmp_arr, SORT_STRING);
        $tmp_str = implode($tmp_arr);
        $tmp_str = sha1($tmp_str);

        return ($tmp_str == $signature);
    }

    /**
     * 获取后台设置token
     */
    private function _get_token()
    {
        $wechat = M('wechat_bindwechat')->select();
        $token = $wechat[0]['token'];
        return $token;
    }

    /**
     * 这里是处理消息的地方，在这里拿到用户发送的字符串
     */
    private function _responseMsg()
    {
        $post_str = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($post_str)) {
            // 解析微信传过来的 XML 内容
            libxml_disable_entity_loader(true);
            $post_obj = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
            //输入类型
            $msgType = $post_obj->MsgType;
            switch ($msgType) {
                case "text":
                    $this->_parseMessage_text($post_obj);
                    break;
                case "event":
                    $this->_parseMessage_event($post_obj);
                    break;
                default:
                    break;
            }
        } else {
            echo "";
            exit;
        }
    }

    /**
     * 解析用户输入的字符串 text
     */
    private function _parseMessage_text($post_obj)
    {
        // TODO: 在这里做一些字符串解析，比如分析某关键字，返回什么信息等等
        // $keyword 用户输入的内容
        $keyword = trim($post_obj->Content);
        if (!empty($keyword)) {
            $this->_parseMessage('textkey',$keyword,$post_obj);
        }
    }

    /**
     * 解析用户输入的字符串 event
     */
    private function _parseMessage_event($post_obj)
    {
        $openid = "$post_obj->FromUserName";
        $Event = $post_obj->Event;
        $EventKey = $post_obj->EventKey;
        switch ($Event) {
            case "subscribe"://关注
                $wechat=M('wechat_bindwechat')->select();
                $appid=$wechat[0]['appid'];
                $appsecret=$wechat[0]['appsecret'];
                $weixin = new Common\WeixinCommon();
                $access_token=$weixin->getAccessToken($appid,$appsecret);
                $wxusers=$weixin->getUserInfoByOpenid($access_token,$openid);
                $dt=array('subscribe'=>$wxusers['subscribe'],'openid'=>$openid,'nickname'=>$wxusers['nickname'],'sex'=>$wxusers['sex'],'language'=>$wxusers['language'],'city'=>$wxusers['city'],'province'=>$wxusers['province'],'country'=>$wxusers['country'],'headimgurl'=>$wxusers['headimgurl'],'subscribe_time'=>$wxusers['subscribe_time']);
                $map['openid']=$openid;
                $user=M('wx_users')->where($map)->find();
                if(count($user)>0){
                    M('wx_users')->where($map)->save($dt);//修改关注者信息
                }else{
                    M('wx_users')->add($dt);//添加关注者信息
                }
                $this->_parseMessage('first','',$post_obj);
                break;
            case "unsubscribe"://取消关注
                $map['openid']=$openid;
                $user=M('wx_users')->where($map)->find();
                if(count($user)>0){
                    $dt['subscribe']=0;
                    M('wx_users')->where($map)->save($dt);//修改关注状态
                }
                break;
            case "CLICK"://菜单点击事件
                $this->_clickMessage($EventKey,$post_obj);
                break;
            default:
                break;
        }
    }

    /**
     * 关注时回复、默认回复、关键词回复
     */
    private function _parseMessage($replytype, $keyword='', $post_obj){
        //查询数据
        $map['replytype'] = $replytype;
        if($keyword!=''){
            $map['keyname'] = $keyword;

            $pros=array();
            $arr=explode('，',$keyword);//先分割中文逗号
            if($arr[0]==$keyword){
                $arr=explode(',',$keyword);//再分割英文逗号
            }
            for($i=0;$i<count($arr);$i++){
                $search=$arr[$i];
                $url = "http://wx.longfor.com/lfgroup/m/project/get_yt?yt_name=$search";
                $datas=get_data($url);
                if(count($datas)>0){
                    $search=$datas['ID'];
                }
                $url = "http://wx.longfor.com/lfgroup/m/project/get_like_pros?keyword=$search";
                $datas=get_data($url);
                foreach($datas as $item){
                    $pros[]=$item;
                }
            }
            $pros=unique_arr($pros,true);//二维数组去重
            if(count($pros)>0&&count($pros)<8){
                $this->news_view($post_obj,$pros);
                return;
            }
        }
        $reply = D("Wechatreply")->relation(true)->where($map)->find();
        if (count($reply) > 0) {
            $type = $reply['wechat_contents']['contenttype'];
            $content = $reply['wechat_contents']['content'];
            $this->_get_reply($type,$content,$post_obj);
        }else {
            //返回默认回复
            echo '';
            exit;
        }
    }

    /**
     * 点击事件回复
     */
    private function _clickMessage($EventKey,$post_obj)
    {
        $map['contentid']=$EventKey;
        $reply=M('wechat_contents')->where(array('contentid'=>"$EventKey"))->find();
//        file_put_contents('Data/log.txt',M('wechat_contents')->GetLastSql(),FILE_APPEND);
//        file_put_contents('Data/log.txt',json_encode($reply),FILE_APPEND);
        if (count($reply) > 0) {
            $type = $reply['contenttype'];
            $content = $reply['content'];
            $this->_get_reply($type,$content,$post_obj);
        }else {
            //返回默认回复
            echo '';
            exit;
        }
    }

    /**
     * 根据类型回复用户
     */
    private function _get_reply($type, $content, $post_obj)
    {
        if ($type == 'text') {
            $content = str_replace("&lt;", "<", $content);
            $content = str_replace("&gt;", ">", $content);
            $content = str_replace("\n", "\r\n", $content);
            $output = '<xml>
                        <ToUserName><![CDATA[' . $post_obj->FromUserName . ']]></ToUserName>
                        <FromUserName><![CDATA[' . $post_obj->ToUserName . ']]></FromUserName>
                        <CreateTime>' . time() . '</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[' . $content . ']]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>';
            echo $output;
            exit;
        } else if ($type == 'news') {
            $output = '<xml>
                            <ToUserName><![CDATA[' . $post_obj->FromUserName . ']]></ToUserName>
                            <FromUserName><![CDATA[' . $post_obj->ToUserName . ']]></FromUserName>
                            <CreateTime>' . time() . '</CreateTime>
                            <MsgType><![CDATA[news]]></MsgType>';
            $item_con = json_decode($content);
            $output .= '<ArticleCount>' . count($item_con) . '</ArticleCount>
                            <Articles>';
            for ($i = 0; $i < count($item_con); $i++) {
                $output .= '<item>
                                <Title><![CDATA[' . $item_con[$i]->detailtitle . ']]></Title>
                                <Description><![CDATA[' . $item_con[$i]->detailintro . ']]></Description>';
                $picurl = 'http://' . $_SERVER['HTTP_HOST'];
                $url = $item_con[$i]->detaillogo;
                $preg = '|^http://|';
                if (preg_match($preg, $url)) {
                    $picurl = $item_con[$i]->detaillogo;
                } else {
                    $picurl .= $item_con[$i]->detaillogo;
                }
                $output .= '<PicUrl><![CDATA[' . $picurl . ']]></PicUrl>';
                if ($item_con[$i]->detaillink != '') {
                    $linkurl = $item_con[$i]->detaillink;
                    $check = strpos($linkurl, '?');
                    //如果存在 ?
                    if ($check !== false) {
                        //如果 ? 后面没有参数，如 http://www.yitu.org/index.php?
                        if (substr($linkurl, $check + 1) == '') {
                            //可以直接加上附加参数
                            $new_url = $linkurl . 'openid=' . $post_obj->FromUserName;
                        } else {//如果有参数，如：http://www.yitu.org/index.php?ID=12
                            $new_url = $linkurl . '&openid=' . $post_obj->FromUserName;
                        }
                    } else {
                        $new_url = $linkurl . '?openid=' . $post_obj->FromUserName;
                    }
                } else {
                    $new_url = 'http://' . $_SERVER['SERVER_NAME'] . U('Admin/Msg/test') . '?id=' . $item_con[$i]->detailid . '&openid=' . $post_obj->FromUserName;
                }
                $output .= '<Url><![CDATA[' . $new_url . ']]></Url>
                                </item>';
            }
            $output .= '</Articles>
                        </xml>';
            echo $output;
            exit;
        }
    }

    /**
     * 关键词回复多图文消息
     */
    function news_view($post_obj,$content){
        $output = '<xml>
                            <ToUserName><![CDATA[' . $post_obj->FromUserName . ']]></ToUserName>
                            <FromUserName><![CDATA[' . $post_obj->ToUserName . ']]></FromUserName>
                            <CreateTime>' . time() . '</CreateTime>
                            <MsgType><![CDATA[news]]></MsgType>';
        $item_con = json_decode($content);
        $output .= '<ArticleCount>' . count($content) . '</ArticleCount>
                            <Articles>';
        foreach ($content as $item) {
            $output .= '<item>
                                <Title><![CDATA[' ."重庆龙湖·". $item['PRO_NAME'] . ']]></Title>
                                <Description><![CDATA[' . $item['PRO_JDMS'] . ']]></Description>';
            $picurl = 'http://wx.longfor.com' . $item['PRO_LOGO'];
            $output .= '<PicUrl><![CDATA[' . $picurl . ']]></PicUrl>';
            $new_url="http://wx.longfor.com/lfgroup/m/project/pro_introduce?id=".$item['ID'];
            $output .= '<Url><![CDATA[' . $new_url . ']]></Url>
                                </item>';
        }
        $output .= '</Articles>
                        </xml>';
        echo $output;
        exit;
    }
}